#include <sslSocket.h>
#include <QFile>
#include <QMessageBox>
#include <QTimer>
#include <QDebug>
#include <QSslConfiguration>

SslClient::SslClient(QObject *parent) :
    QObject(parent),
    sslsocket(new QSslSocket(this))
{
    connect(sslsocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(onSslErrors(QList<QSslError>)));
    loadCaCertificate("F:/Desktop/lib/ca.crt");
}

SslClient::~SslClient()
{
}

void SslClient::loadCaCertificate(const QString &path) {
    QFile certFile(path);
    if (certFile.open(QIODevice::ReadOnly)) {
        QSslCertificate cert(&certFile, QSsl::Pem);
        QList<QSslCertificate> certs;
        certs.append(cert);
        QSslConfiguration sslConfig = sslsocket->sslConfiguration();
        sslConfig.setCaCertificates(certs);
        sslsocket->setSslConfiguration(sslConfig);
    } else {
        qDebug() << "Failed to load CA certificate";
    }
}

void SslClient::sendRegistrationData(const QString &username, const QString &password) {
    sslsocket->setPeerVerifyMode(QSslSocket::VerifyPeer);
    if(sslsocket->state() != QSslSocket::ConnectedState) {
        sslsocket->connectToHostEncrypted("111.231.80.52", 8935);
        if(!sslsocket->waitForEncrypted(5000)) {
            emit registrationResponse("网络异常，请重试");
            return;
        }
    }

    QByteArray dataToSend = (username + " " + password).toUtf8();
    sslsocket->write(dataToSend);
    sslsocket->flush();

    if(sslsocket->waitForReadyRead(5000)) {
        QByteArray data = sslsocket->readAll();
        QString response = QString::fromUtf8(data);
        emit registrationResponse(response);
    } else {
        emit registrationResponse("注册异常");
    }
}

void SslClient::onSslErrors(const QList<QSslError> &errors) {
    foreach (const QSslError &error, errors) {
        qWarning() << "SSL Error:" << error.errorString();
    }
    sslsocket->ignoreSslErrors();
}
